package nc.bs.hrppl.pjapplication.ace.bp.rule;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.hrppl.pjapplication.plugin.bpplugin.PjapplicationPluginPoint;
import nc.impl.pub.util.db.InSqlManager;
import nc.impl.pubapp.pattern.data.bill.template.InsertBPTemplate;
import nc.impl.pubapp.pattern.rule.ICompareRule;
import nc.itf.pmpub.prv.IProject;
import nc.vo.hrppl.pjapplication.*;
import nc.vo.org.DeptVO;
import nc.vo.pmpub.project.ProjectBillVO;
import nc.vo.pmpub.project.ProjectBodyVO;
import nc.vo.pmpub.project.ProjectHeadVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pubapp.AppContext;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;

public class VersionProcessRule implements ICompareRule<AggPjapplVO> {
	public void process(AggPjapplVO[] bills, AggPjapplVO[] originBills) {
		try {
			List<AggPjapplVO> hisAggvos = new ArrayList<AggPjapplVO>();

			for (int i = 0; i < bills.length; i++) {
				if (bills[i].getParentVO().getVersionno().compareTo(originBills[i].getParentVO().getVersionno()) > 0) {
					// 项目库的数据才允许修订pjlibcategorystatus = 4;
					//2024630 项目监管允许修订
					if (originBills[i].getParentVO().getPjlibcategory() != 3 && originBills[i].getParentVO().getPjlibcategory() != 4) {
						ExceptionUtils.wrappBusinessException("项目库类别为备选库，项目库才可以修订!");
					}
					hisAggvos.add(buildHistoryBill(originBills[i]));

//					for (int i = 0; i < updatevo.length; i++) {
//						if ( updatevo[i].getParentVO().getPjlibcategory() == 4 ) {
//							String apj = updatevo[i].getPrimaryKey();
//							updateProject(new String[]{apj},updatevo);
//						}
//            		}
					if ( bills[i].getParentVO().getPjlibcategory() == 4 ) {
						String apj = bills[i].getParentVO().getPrimaryKey();
						updateProject(new String[]{apj}, new AggPjapplVO[]{bills[i]});
					}

				}
			}

			if (hisAggvos.size() > 0) {
				InsertBPTemplate bp = new InsertBPTemplate(PjapplicationPluginPoint.INSERT);
				AggPjapplVO[] insResults = (AggPjapplVO[]) bp.insert(hisAggvos.toArray(new AggPjapplVO[0]));

				String[] insBillIds = new String[insResults.length];
				for (int i = 0; i < insResults.length; i++) {
					insBillIds[i] = insResults[i].getPrimaryKey();
				}

				InSqlManager insqlManager = new InSqlManager();
				String inSql = InSqlManager.getInSQLValue(insBillIds);
				String sql = "update hrppl_pjappl set dr = 99 where pk_pjappl in " + inSql;
				new BaseDAO().executeUpdate(sql);
			}
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException("处理修订历史版本异常：" + e.getMessage());
		}
	}

	private void updateProject(String[] apj,AggPjapplVO[] clientFullVOs) throws BusinessException {
		ProjectBillVO[] pbvos = NCLocator.getInstance().lookup(nc.itf.pmpub.prv.IProjectQuery.class)
				.queryProjectBillVOsBypks(apj);

		IProject lookup = NCLocator.getInstance().lookup(nc.itf.pmpub.prv.IProject.class);

		if (pbvos != null && pbvos.length > 0) {
			// 如果存在名称相同的项目，则将项目-项目组织的项目编码更新至项目申请中，其他字段按照以上规则同步
			ProjectBillVO[] projects = covertvotovo(clientFullVOs, pbvos);
			for (ProjectBillVO project : projects) {
				lookup.update(new ProjectBillVO[]{project});
			}
		} else {
			ProjectBillVO[] projects = covertvotovo(clientFullVOs, null);
			for (ProjectBillVO project : projects) {
				lookup.insert(new ProjectBillVO[]{project});
			}

		}
	}

	public ProjectBillVO[] covertvotovo(AggPjapplVO[] aggPjapplVOS, ProjectBillVO[] pbvos) throws BusinessException {
		if (aggPjapplVOS != null) {
			// 编码billno->project_code,名称pjname->project_name,主键:pk_pjappl,pk_project
			// 项目曾用名称pjusename->project_ot_name,项目类型pjtype->pk_eps,责任人headuser->pk_dutier,
			// 开始时间startingdate->plan_start_date,结束日期closingdate->plan_finish_date
//            ProjectBillVO[] pbvoarr = new ProjectBillVO[aggPjapplVOS.length];
			ArrayList<ProjectBillVO> result = new ArrayList<>();
			//字段转化关系
			String[] fieldtofield = new String[]{"billno,project_code", "pjname,project_name",
					"pjusename,project_ot_name", "pjtype,pk_eps", "headuser,pk_dutier", "startingdate,plan_start_date",
					"closingdate,plan_finish_date", "pk_pjappl,pk_project", "pk_group,pk_group",
					"belongpro,pk_parentpro", "officedept,pk_duty_dept_v", "governmentpurchase,govpurch",
					"addedassetallocation,assetallocation","applyyear,nyear", "bperformance,bperformance"};

			for (int i = 0; i < aggPjapplVOS.length; i++) {
				AggPjapplVO aggPjapplVO = aggPjapplVOS[i];
				if (aggPjapplVO.getParentVO().getPjlibcategory() != 4){
					continue;
				}
				ProjectBillVO projectBillVO = new ProjectBillVO();
				if(Objects.nonNull(pbvos)){
					projectBillVO = (ProjectBillVO) pbvos[0].clone();
					projectBillVO.getParentVO().setStatus(VOStatus.UPDATED);
				}else{
					projectBillVO.setParentVO(new ProjectHeadVO());
				}
				// 表头信息
				for (int j = 0; j < fieldtofield.length; j++) {
					String[] fieldv = fieldtofield[j].split(",");
					Object attributeValue = aggPjapplVO.getParent().getAttributeValue(fieldv[0]);
					if (attributeValue != null) {
						if (fieldv[0].equals("officedept"))
						{
							Collection<DeptVO> dept = new BaseDAO().retrieveByClause(DeptVO.class, "pk_dept='" + attributeValue.toString() + "'");
							projectBillVO.getParentVO().setAttributeValue(fieldv[1], dept.toArray(new DeptVO[0])[0].getPk_vid());
							projectBillVO.getParentVO().setAttributeValue("pk_duty_dept", attributeValue);
						}
						else
						{
							projectBillVO.getParentVO().setAttributeValue(fieldv[1], attributeValue);
						}

					}
				}
				// 补齐其他信息
				projectBillVO.getParentVO().setPk_org(aggPjapplVO.getParentVO().getPk_org());
				projectBillVO.getParentVO().setPk_group(aggPjapplVO.getParentVO().getPk_group());
				projectBillVO.getParentVO().setPk_org_v(aggPjapplVO.getParentVO().getPk_org_v());
				projectBillVO.getParentVO().setFilesource(1);
				// 默认启用
				projectBillVO.getParentVO().setEnablestate(2);

				//如果是集团项目 则进入 项目-集团节点
				if (aggPjapplVO.getParentVO().getIsgroup().booleanValue()) {
					projectBillVO.getParentVO().setPk_org(aggPjapplVO.getParentVO().getPk_group());
				}

				// 是否来源项目库：Y
				projectBillVO.getParentVO().setAttributeValue("isfromhrppl", UFBoolean.TRUE);

				// 子表信息处理
				ProjectBodyVO projectBodyVO = new ProjectBodyVO();
				if(Objects.nonNull(pbvos)){
					projectBodyVO = pbvos[0].getProjectBodyVO()[0];
					projectBodyVO.setStatus(VOStatus.UPDATED);
				}

				projectBodyVO.setPk_org(aggPjapplVO.getParentVO().getPk_org());
				projectBodyVO.setPk_org_v(aggPjapplVO.getParentVO().getPk_org_v());
				projectBodyVO.setPk_parti_org(aggPjapplVO.getParentVO().getPk_org());
				projectBodyVO.setPk_parti_org_v(aggPjapplVO.getParentVO().getPk_org_v());
				projectBodyVO.setPk_group(aggPjapplVO.getParentVO().getPk_group());

				projectBillVO.setChildrenVO(new ProjectBodyVO[]{projectBodyVO});

				result.add(projectBillVO);
			}
			if (result.size() > 0) {
				return result.toArray(new ProjectBillVO[result.size()]);
			}else {
				return new ProjectBillVO[0];
			}
		}
		return new ProjectBillVO[0];
	}

	private AggPjapplVO buildHistoryBill(AggPjapplVO originBill) throws BusinessException {
		AggPjapplVO hisAggvo = (AggPjapplVO) originBill.clone();
		PJApplHVO hvo = hisAggvo.getParentVO();

		hvo.setStatus(2);

		String billversionpk = new String(hvo.getPrimaryKey());

		hvo.setPrimaryKey(null);

		hvo.setIslastversion(UFBoolean.FALSE);

		String endstr = "_" + hvo.getVersionno().setScale(1, 4).toString();
		hvo.setBillno(hvo.getBillno() + endstr);
		hvo.setCode(hvo.getCode() + endstr);
		hvo.setPjname(hvo.getPjname() + endstr);

		hvo.setModifier(AppContext.getInstance().getPkUser());

		hvo.setModifiedtime(AppContext.getInstance().getServerTime());

		hvo.setBillversionpk(billversionpk);

		SuperVO[] childVos = (SuperVO[]) hisAggvo.getChildren(PjapplBVO.class);
		if (childVos != null) {
			for (int i = 0; i < childVos.length; i++) {
				childVos[i].setStatus(2);
				childVos[i].setPrimaryKey(null);
				childVos[i].setAttributeValue("pk_pjappl", null);
			}
		}

		SuperVO[] childcVos = (SuperVO[]) hisAggvo.getChildren(PjapplCVO.class);
		if (childcVos != null) {
			for (int i = 0; i < childcVos.length; i++) {
				childcVos[i].setStatus(2);
				childcVos[i].setPrimaryKey(null);
				childcVos[i].setAttributeValue("pk_pjappl", null);
			}
		}

		SuperVO[] childpVos = (SuperVO[]) hisAggvo.getChildren(PjapplPVO.class);
		if (childpVos != null) {
			for (int i = 0; i < childpVos.length; i++) {
				childpVos[i].setStatus(2);
				childpVos[i].setPrimaryKey(null);
				childpVos[i].setAttributeValue("pk_pjappl", null);
			}
		}

		return hisAggvo;
	}
}